import { showMessage } from '@/components/antd-comp/message'
import { startInputParams } from '@/pages/workflow/constants'
import { checkArrayItems, checkArrayItemsRepeat } from '@/pages/workflow/utils'
import { PlusOutlined } from '@ant-design/icons'
import { Button } from 'antd'
import { produce } from 'immer'
import React, { FC, useCallback } from 'react'
import { INPUT_CONSTRAINTS } from '../../../components/InspectData'
import '../../../style/index.less'
import { InputVar, MoreInfo } from '../../types'
import ParamItem from './ParamItem'
type Props = {
  readonly: boolean
  list: InputVar[]
  info: any
  onChange: (list: InputVar[], moreInfo?: { index: number; payload: MoreInfo }) => void
}

const ParamList: FC<Props> = ({ readonly, list, info, onChange }) => {
  const handleVarChange = useCallback(
    (index: number) => {
      return (payload: InputVar, moreInfo?: MoreInfo) => {
        const newList = produce(list, draft => {
          draft[index] = payload
        })
        onChange(newList, moreInfo ? { index, payload: moreInfo } : undefined)
      }
    },
    [list, onChange]
  )

  const handleVarRemove = useCallback(
    (index: number) => {
      return () => {
        const newList = produce(list, draft => {
          draft.splice(index, 1)
        })
        onChange(newList, undefined)
      }
    },
    [list, onChange]
  )

  const addItem = () => {
    if (list.length === INPUT_CONSTRAINTS.VARIABLE_CONT) {
      showMessage({
        content: INPUT_CONSTRAINTS.VARIABLE_CONT_TITLE + INPUT_CONSTRAINTS.VARIABLE_CONT,
        type: 'warning'
      })
      return
    }
    const newList = produce(list, draft => {
      draft.push({ ...startInputParams() })
    })
    onChange(newList, undefined)
  }

  return (
    <div className="cursor-default" draggable="false">
      {list.map((item, index) => (
        <ParamItem
          key={item.id}
          readonly={readonly}
          payload={item}
          itemIndex={index}
          onChange={handleVarChange(index)}
          onRemove={handleVarRemove(index)}
        />
      ))}
      {!checkArrayItems(list, ['variable', 'label']) ? (
        <div className="custom-params-invalid mt-[8px]">勾选必填时：变量和描述不能为空</div>
      ) : (
        !checkArrayItemsRepeat(list, ['variable']) && (
          <div className="custom-params-invalid">勾选必填时：变量不能重复</div>
        )
      )}
      <Button onClick={addItem} className="mt-[8px]" icon={<PlusOutlined />}>
        新增
      </Button>
    </div>
  )
}
export default React.memo(ParamList)
